<script setup lang="ts">
defineOptions({
  name: "uploadFiles"
});
import { ref, reactive, onMounted, getCurrentInstance, watch } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { PxMessage } from "px-ui";
import importFiles from "@/views/common/components/importFiles/index.vue";
import { queryChildByTypeCodeAndItemValue, importReport } from "@/api/machineClass";
import { querySystemSelect } from "@/api/equip/archive";
import { useThrottleFn } from "@vueuse/core";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { throttleDelay as delay } from "@/utils/constant";

interface Props {
  // 弹框类型 add 新增   edit 编辑
  type?: "add" | "edit";
  id?: string;
}

const props = withDefaults(defineProps<Props>(), {});

const dialogVisible = defineModel({ type: Boolean, default: false });

interface RuleForm {
  samplePersonId: string;
  samplePerson: string;
  sampleLocation: string;
  // system: string;
  detectOrganization: string;
  responsiblePersonId: string;
  responsiblePerson: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  samplePersonId: "",
  samplePerson: "",
  sampleLocation: "",
  // system: "",
  detectOrganization: "",
  responsiblePersonId: "",
  responsiblePerson: ""
});

const organizationArr = ref<any>([]);
const locationArr = ref<any>([]);
const peopleList = ref<any>([]);

const rules = reactive<FormRules<RuleForm>>({
  detectOrganization: [{ required: true, message: "请选择检测机构", trigger: "change" }],
  samplePersonId: [{ required: true, message: "请选择取样人", trigger: "change" }],
  samplePerson: [{ required: true, message: "请选择取样人", trigger: "blur" }],
  sampleLocation: [{ required: true, message: "请选择取样点", trigger: "change" }],
  responsiblePersonId: [{ required: true, message: "请选择本科负责人", trigger: "change" }]
  // system: [{ required: true, message: "请选择系统", trigger: "blur" }],
});

const importFile = ref<any>({});
const gasNameOptions = ref({});

const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};

const { proxy }: any = getCurrentInstance();

const downloadFn = useThrottleFn(async () => {
  // const url = "";
  // const form = new FormData();
  // proxy.download("post", url, form);
}, delay);

const emits = defineEmits(["submit"]);

const cancelHandler = () => {
  dialogVisible.value = false;
};

const submitHandler = useThrottleFn(async () => {
  const { file = "" } = importFile.value;
  console.log("importFile.value  ", importFile.value);
  // return;
  if (!file) {
    PxMessage.error("请上传 报告 ！");
    return;
  }
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let fileFormData = new FormData();
      for (const key in ruleForm) {
        fileFormData.append(key, ruleForm[key]);
      }
      // const { file = "" } = importFile.value;
      file && fileFormData.append("file", file);
      await importReport(fileFormData);
      emits("submit");
      dialogVisible.value = false;
      // ruleFormRef.value.resetFileds();
      // importFile.value = {};
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);

const samplePersonIdChange = (val: any) => {
  ruleForm.samplePerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};
const responsiblePersonIdChange = (val: any) => {
  ruleForm.responsiblePerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};

const init = async () => {
  gasNameOptions.value = await querySystemSelect({ factoryArea: "", className: "MACHINE" });
};

onMounted(async () => {
  // await init();
  peopleList.value = await getEmployeeIdAndName(["MACHINE"]);
  queryChildByTypeCodeAndItemValue({
    value: "DU01",
    typeCode: "MCTS"
  }).then((res: any) => {
    organizationArr.value = res ? res : [];
  });
  queryChildByTypeCodeAndItemValue({
    value: "CSP01",
    typeCode: "MCTS"
  }).then((res: any) => {
    locationArr.value = res ? res : [];
  });
});
</script>

<template>
  <px-dialog v-model="dialogVisible" title="导入报告" :width="600">
    <div class="import-bottle">
      <div class="import-bottle-title">
        上传前请先
        <a
          :href="proxy.useGetStaticUrl(`/ifp-web-static/file/xlsx/NALCO 北方集成电路技术创新中心 PSR 2024.10.22.xlsx`)"
          download="水质检测导入模板.xlsx"
          ><span class="download"> 下载模板 </span></a
        >
        ，填写完成后导入数据
      </div>
      <div class="import-bottle-upload">
        <importFiles v-model="importFile" isNotImmediateUpload />
      </div>
      <px-form ref="ruleFormRef" :model="ruleForm" :rules="rules" inline label-width="100px" class="demo-ruleForm" status-icon>
        <px-row :gutter="32">
          <px-col :span="24">
            <px-form-item label="检测机构" prop="detectOrganization">
              <px-select v-model="ruleForm.detectOrganization" filterable clearable placeholder="请选择检测机构">
                <px-option v-for="item in organizationArr" :key="item.itemValue" :label="item.itemName" :value="item.itemValue" />
              </px-select>
            </px-form-item>
          </px-col>
          <!-- <px-col :span="24">
            <px-form-item label="取样人" prop="samplePersonId">
              <px-select v-model="ruleForm.samplePersonId" filterable clearable placeholder="请选择取样人" @change="samplePersonIdChange">
                <px-option v-for="item in peopleList" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col> -->
          <px-col :span="24">
            <px-form-item label="取样人" prop="samplePerson">
              <px-input v-model="ruleForm.samplePerson" placeholder="请输入取样人" clearable />
            </px-form-item>
          </px-col>
          <!-- <px-col :span="24">
            <px-form-item label="系统" prop="system">
              <px-tree-select
                v-model="ruleForm.system"
                clearable
                style="width: 100%"
                placeholder="请选择系统"
                :props="defaultProps"
                :data="gasNameOptions"
                check-strictly
                :render-after-expand="false"
              />
            </px-form-item>
          </px-col> -->
          <px-col :span="24">
            <px-form-item label="取样点" prop="sampleLocation">
              <px-select v-model="ruleForm.sampleLocation" filterable clearable placeholder="请选择取样点">
                <px-option v-for="item in locationArr" :key="item.itemValue" :label="item.itemName" :value="item.itemValue" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="24">
            <px-form-item label="本科负责人" prop="responsiblePersonId">
              <px-select
                v-model="ruleForm.responsiblePersonId"
                filterable
                clearable
                placeholder="请选择本科负责人"
                @change="responsiblePersonIdChange"
              >
                <px-option v-for="item in peopleList" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
.import-bottle {
  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin-bottom: 24px;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      color: #3b82f6;
    }
  }

  .import-bottle-upload {
    width: 100%;
    margin-bottom: 24px;
  }
}

:deep(.px-form-item) {
  width: 100%;

  .px-form-item__content {
    .px-input,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
